<!--
  @Description:搭配套餐分页查询
  @Author:zqy
  @Date:2024-08-26 10:23:00
  @Last Modified by:zqy
  @Last Modified time:2024-08-26 10:23:00
-->
<template>
  <el-dialog
    ref="refDlg"
    v-el-drag-dialog
    width="800px"
    title="搭配套餐选择"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @close="closeDialog"
  >
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="选择" name="first">
        <table-box
          ref="refAllTable"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          :table-height="400"
          table-row-key="id"
          show-selection
          :selected-arry.sync="tableSelected"
          :table-row-class-name="tableRowClassName"
          :show-custom-setting="false"
          :show-custom-combine="false"
          :table-sortable="false"
          @data-change="tableDataChange"
          @selection-change="handleSelectionChange"
        />
        <!-- @row-dblclick="dbClickRow" -->
      </el-tab-pane>
      <el-tab-pane :label="`已选(${selectedProductData.length})`" name="second">
        <div class="table-list-box">
          <el-table
            style="width: 100%"
            :data="selectedProductData"
            :height="480"
            header-row-class-name="table-list-header"
            highlight-current-row
            border
          >
            <el-table-column type="index" label="序号" width="50" fixed="left" />
            <el-table-column prop="name" label="搭配名称" min-width="200" />
            <el-table-column prop="lastUpdateTime" label="最后修改时间" width="150" />
            <el-table-column prop="lastUpdateBy" label="最后修改人" width="150" />
            <el-table-column label="操作" width="80" fixed="right">
              <template v-slot="{row}">
                <el-button class="my-button" type="text" size="mini" @click="handleDeleteSelected(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'DlgProductCombinationList',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      otherFilters: [
        { id: 'enabled', property: 'enabled', operator: '=', value: 1 }
      ],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/productCombination/voPage`,
        onlySearchBar: true,
        tabIndex: 997,
        sort: 'lastUpdateTime',
        order: 'desc',
        setting: [
          {
            prop: 'name',
            label: '搭配名称',
            minWidth: 200
          },
          {
            prop: 'createBy',
            label: '创建人',
            width: 120,
            type: 'hidden'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 150,
            type: 'hidden'
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            width: 120,
            type: 'hidden'
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            width: 150,
            type: 'hidden'
          }
        ]
      },
      activeName: 'first',
      tableSelected: [], // 单选行
      selectedProductData: [], // 当前已选所有商品
      cancelSelectedProducts: [], // 临时存储非当前页的移除数据
      currentTableData: [], // 当前页表格数据
      allProductData: {} // 当前所查询的所有数据
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    allProductData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    }
    /* selectedId: {
      handler(val, oldVal) {
        const ids = val ? val.split('|') : []
        this.$nextTick(() => {
          this.initSelections(ids)
        })
      },
      immediate: true
    } */
  },
  methods: {
    handleClick() {

    },
    closeDialog() {
      this.$refs.refAllTable.clearSelection()
      this.selectedProductData = []
      this.tableSelected = []
      this.dialogShow = false
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedProductData.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : 'white-row'
    },
    tableDataChange(res) {
      if (res && res.data && res.data.records) {
        const { page } = res.data
        const list = res.data.records
        this.currentTableData = list
        const selectKey = `${page}`
        if (this.allProductData[selectKey]) {
          this.allProductData[selectKey] = []
        }
        this.$set(this.allProductData, selectKey, list)
      }
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$refs.refAllTable.initTableData(isInit ? '' : 'onPage')
    },
    // 重置当前页已选中产品的复选状态
    reSetTableSelection() {
      const cancelList = this.cancelSelectedProducts.filter(item => {
        const tmp = this.currentTableData.find(v => v.id === item.id)
        if (tmp && tmp.id) { // 在当前页表格数据中则取消选中
          this.$refs.refAllTable.toggleRowSelection(item, false)
        }
        return tmp.length === 0 // 返回非当前页数据
      })
      this.cancelSelectedProducts = cancelList

      const initCheckedRows = []
      this.currentTableData.forEach(item => {
        const index = this.selectedProductData.findIndex(v => v.id === item.id)
        const tmp = this.selectedProductData[index] || null
        if (tmp && tmp.id) {
          // 在当前页表格数据中数据选中
          this.selectedProductData.splice(index, 1)
          this.$refs.refAllTable.toggleRowSelection(tmp, false)
          initCheckedRows.push(item)
        }
      })
      initCheckedRows.forEach(item => {
        this.$refs.refAllTable.toggleRowSelection(item, true)
      })
    },
    // 产品复选框操作
    handleSelectionChange(rows) {
      const { selectedProductData = [] } = this
      // 过滤掉非当前页已删除的产品
      const enbleSelectRows = rows.filter(row => {
        const index = this.cancelSelectedProducts.findIndex(v => v.id === row.id)
        return index === -1
      })

      this.selectedProductData = enbleSelectRows.map(row => {
        // 检测当前复选行是否已选中
        const repeatPros = selectedProductData.filter(v => v.id === row.id)
        if (repeatPros && repeatPros.length) {
          return repeatPros[0] // 已选中
        } else {
          return row // 新添加
        }
      })
    },
    // 移除已选择产品
    handleDeleteSelected(row) {
      const tmp = this.currentTableData.filter(item => row.id === item.id)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refAllTable.toggleRowSelection(tmp[0], false)
        const index = this.selectedProductData.findIndex(v => v.id === tmp[0].id)
        if (index > -1) {
          this.selectedProductData.splice(index, 1)
        }
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选产品表中删除
        let tmpArr = []
        for (const key in this.allProductData) {
          tmpArr = tmpArr.concat(this.allProductData[key])
        }
        const repeatRows = tmpArr.filter(item => row.id === item.id)
        if (repeatRows && repeatRows.length) {
          this.$refs.refAllTable.toggleRowSelection(repeatRows[0], false)
        }
        this.cancelSelectedProducts.push(row)
        const index = this.selectedProductData.findIndex(v => v.id === row.id)
        if (index > -1) {
          this.selectedProductData.splice(index, 1)
        }
      }
    },
    dbClickRow(row, e) {
      this.tableSelected = [row]
      this.handleSure()
    },
    handleSure() {
      if (this.selectedProductData.length === 0) {
        this.$message.warning('请至少选择一个搭配套餐')
        return
      }
      const data = this.selectedProductData.map(v => {
        return {
          id: v.id,
          name: v.name
        }
      })
      this.$emit('change', data)
      this.closeDialog()
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
